package com.ara.common.kernel.address;

import android.content.Context;
import android.content.res.AssetManager;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.ara.common.kernel.R;
import com.ara.common.kernel.listener.OnDialogListener;
import com.ara.common.kernel.network.util.GsonUtils;
import com.ara.common.kernel.util.LoggerUtils;
import com.ara.common.kernel.util.ScreenUtils;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by XieXin on 2019/4/2.
 * 省市区帮助类
 */
public class ProvinceUtils {
    private static List<ProvinceBean> provinces;
    private static List<ArrayList<String>> citys;
    private static List<ArrayList<ArrayList<String>>> areas;


    /**
     * 获取省市区列表
     *
     * @param context
     * @return
     */
    public static List<ProvinceBean> getProvinces(Context context) {
        StringBuilder json = new StringBuilder();
        BufferedReader br = null;
        try {
            AssetManager assetManager = context.getAssets();
            br = new BufferedReader(
                    new InputStreamReader(assetManager.open("area.json")));
            String line;
            while ((line = br.readLine()) != null) {
                json.append(line);
            }
        } catch (IOException e) {
            LoggerUtils.e(e.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    LoggerUtils.e(e.getMessage());
                }
            }
        }
        return GsonUtils.toList(json.toString(), ProvinceBean.class);
    }

    /**
     * 获取省市区选择器
     *
     * @return
     */
    public static OptionsPickerView getProvince(Context context, String title, int colorResId, int textColorResId,
                                                OnOptionsSelectListener listener) {
        OptionsPickerView options = new OptionsPickerBuilder(context, listener)
                .setTitleText(title)
                .setDividerColor(ContextCompat.getColor(context, colorResId))
                .setTextColorCenter(ContextCompat.getColor(context, textColorResId))
                .setCancelColor(ContextCompat.getColor(context, colorResId))
                .setSubmitColor(ContextCompat.getColor(context, colorResId))
                .setContentTextSize(16)
                .setLineSpacingMultiplier(2.5f)
                .isDialog(true)
                .build();

        provinces = ProvinceUtils.getProvinces(context);
        citys = new ArrayList<>();
        areas = new ArrayList<>();
        for (int i = 0; i < provinces.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> provinceAreaList = new ArrayList<>();//该省的所有地区列表（第三级）
            ProvinceBean provinceBean = provinces.get(i);
            for (int j = 0; j < provinces.get(i).getChildren().size(); j++) {//遍历该省份的所有城市
                String cityName = provinces.get(i).getChildren().get(j).getName();
                cityList.add(cityName);//添加城市

                ArrayList<String> areaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (provinces.get(i).getChildren().get(j).getChildren() == null ||
                        provinces.get(i).getChildren().get(j).getChildren().size() == 0) {
                    areaList.add("");
                } else {
                    for (int k = 0; k < provinces.get(i).getChildren().get(j).getChildren().size(); k++) {//该城市对应地区所有数据
                        String areaName = provinces.get(i).getChildren().get(j).getChildren().get(k).getName();
                        areaList.add(areaName);//添加该城市所有地区数据
                    }
                }
                provinceAreaList.add(areaList);//添加该省所有地区数据
            }
            citys.add(cityList);//添加城市数据
            areas.add(provinceAreaList);//添加地区数据
        }
        options.setPicker(provinces, citys, areas);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        options.getDialogContainerLayout().setLayoutParams(params);

        //获取当前Activity所在的窗体
        Window dialogWindow = options.getDialog().getWindow();
        //获得窗体的属性
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth(context);
            //将属性设置给窗体
            dialogWindow.setAttributes(lp);
            //底部
            dialogWindow.setGravity(Gravity.BOTTOM);
        }
        return options;
    }

    /**
     * 获取省市区选择器
     *
     * @return
     */
    public static OptionsPickerView getProvince(Context context, String title, int colorResId, int textColorResId,
                                                OnOptionsSelectListener listener, OnDialogListener onDialogListener) {
        OptionsPickerView options = new OptionsPickerBuilder(context, listener)
                .setLayoutRes(R.layout.pickerview_custom_options, v -> {
                    //自定义布局中的控件初始化及事件处理
                    final TextView tvTitle = v.findViewById(R.id.tv_title);
                    final ImageView ivClose = v.findViewById(R.id.iv_close);
                    final TextView tvCancel = v.findViewById(R.id.tv_cancel);
                    final TextView tvConfirm = v.findViewById(R.id.tv_confirm);
                    tvTitle.setText(title);
                    ivClose.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onClose();

                    });
                    tvCancel.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onCancel();
                    });
                    tvConfirm.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onConfirm();
                    });
                })
                .setTitleText(title)
                .setDividerColor(ContextCompat.getColor(context, colorResId))
                .setTextColorCenter(ContextCompat.getColor(context, textColorResId))
                .setCancelColor(ContextCompat.getColor(context, colorResId))
                .setSubmitColor(ContextCompat.getColor(context, colorResId))
                .setContentTextSize(16)
                .setOutSideCancelable(false)
                .setLineSpacingMultiplier(2.5f)
                .isDialog(true)
                .build();

        provinces = ProvinceUtils.getProvinces(context);
        citys = new ArrayList<>();
        areas = new ArrayList<>();
        for (int i = 0; i < provinces.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> provinceAreaList = new ArrayList<>();//该省的所有地区列表（第三级）

            for (int j = 0; j < provinces.get(i).getChildren().size(); j++) {//遍历该省份的所有城市
                String cityName = provinces.get(i).getChildren().get(j).getName();
                cityList.add(cityName);//添加城市

                ArrayList<String> areaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (provinces.get(i).getChildren().get(j).getChildren() == null ||
                        provinces.get(i).getChildren().get(j).getChildren().size() == 0) {
                    areaList.add("");
                } else {
                    for (int k = 0; k < provinces.get(i).getChildren().get(j).getChildren().size(); k++) {//该城市对应地区所有数据
                        String areaName = provinces.get(i).getChildren().get(j).getChildren().get(k).getName();
                        areaList.add(areaName);//添加该城市所有地区数据
                    }
                }
                provinceAreaList.add(areaList);//添加该省所有地区数据
            }
            citys.add(cityList);//添加城市数据
            areas.add(provinceAreaList);//添加地区数据
        }
        options.setPicker(provinces, citys, areas);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        options.getDialogContainerLayout().setLayoutParams(params);

        //获取当前Activity所在的窗体
        Window dialogWindow = options.getDialog().getWindow();
        //获得窗体的属性
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth(context);
            //将属性设置给窗体
            dialogWindow.setAttributes(lp);
            //底部
            dialogWindow.setGravity(Gravity.BOTTOM);
        }
        return options;
    }

    /**
     * 获取省市区选择器
     *
     * @return
     */
    public static OptionsPickerView getProvince(Context context, String title, int colorResId, int textColorResId,
                                                String cancel, String confirm,
                                                OnOptionsSelectListener listener, OnDialogListener onDialogListener) {
        OptionsPickerView options = new OptionsPickerBuilder(context, listener)
                .setLayoutRes(R.layout.pickerview_custom_options, v -> {
                    //自定义布局中的控件初始化及事件处理
                    final TextView tvTitle = v.findViewById(R.id.tv_title);
                    final ImageView ivClose = v.findViewById(R.id.iv_close);
                    final TextView tvCancel = v.findViewById(R.id.tv_cancel);
                    final TextView tvConfirm = v.findViewById(R.id.tv_confirm);
                    tvTitle.setText(title);
                    tvCancel.setText(cancel);
                    tvConfirm.setText(confirm);
                    ivClose.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onClose();

                    });
                    tvCancel.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onCancel();
                    });
                    tvConfirm.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onConfirm();
                    });
                })
                .setTitleText(title)
                .setDividerColor(ContextCompat.getColor(context, colorResId))
                .setTextColorCenter(ContextCompat.getColor(context, textColorResId))
                .setCancelColor(ContextCompat.getColor(context, colorResId))
                .setSubmitColor(ContextCompat.getColor(context, colorResId))
                .setContentTextSize(16)
                .setOutSideCancelable(false)
                .setLineSpacingMultiplier(2.5f)
                .isDialog(true)
                .build();

        provinces = ProvinceUtils.getProvinces(context);
        citys = new ArrayList<>();
        areas = new ArrayList<>();
        for (int i = 0; i < provinces.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> provinceAreaList = new ArrayList<>();//该省的所有地区列表（第三级）

            for (int j = 0; j < provinces.get(i).getChildren().size(); j++) {//遍历该省份的所有城市
                String cityName = provinces.get(i).getChildren().get(j).getName();
                cityList.add(cityName);//添加城市

                ArrayList<String> areaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (provinces.get(i).getChildren().get(j).getChildren() == null ||
                        provinces.get(i).getChildren().get(j).getChildren().size() == 0) {
                    areaList.add("");
                } else {
                    for (int k = 0; k < provinces.get(i).getChildren().get(j).getChildren().size(); k++) {//该城市对应地区所有数据
                        String areaName = provinces.get(i).getChildren().get(j).getChildren().get(k).getName();
                        areaList.add(areaName);//添加该城市所有地区数据
                    }
                }
                provinceAreaList.add(areaList);//添加该省所有地区数据
            }
            citys.add(cityList);//添加城市数据
            areas.add(provinceAreaList);//添加地区数据
        }
        options.setPicker(provinces, citys, areas);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        options.getDialogContainerLayout().setLayoutParams(params);

        //获取当前Activity所在的窗体
        Window dialogWindow = options.getDialog().getWindow();
        //获得窗体的属性
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth(context);
            //将属性设置给窗体
            dialogWindow.setAttributes(lp);
            //底部
            dialogWindow.setGravity(Gravity.BOTTOM);
        }
        return options;
    }

    /**
     * 获取省市选择器
     *
     * @return
     */
    public static OptionsPickerView getProvinceCity(Context context, String title, int colorResId, int textColorResId,
                                                    OnOptionsSelectListener listener) {
        OptionsPickerView options = new OptionsPickerBuilder(context, listener)
                .setTitleText(title)
                .setDividerColor(ContextCompat.getColor(context, colorResId))
                .setTextColorCenter(ContextCompat.getColor(context, textColorResId))
                .setCancelColor(ContextCompat.getColor(context, colorResId))
                .setSubmitColor(ContextCompat.getColor(context, colorResId))
                .setContentTextSize(16)
                .setLineSpacingMultiplier(2.5f)
                .isDialog(true)
                .build();

        provinces = ProvinceUtils.getProvinces(context);
        citys = new ArrayList<>();
        for (int i = 0; i < provinces.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）

            for (int j = 0; j < provinces.get(i).getChildren().size(); j++) {//遍历该省份的所有城市
                String cityName = provinces.get(i).getChildren().get(j).getName();
                cityList.add(cityName);//添加城市
            }
            citys.add(cityList);//添加城市数据
        }
        options.setPicker(provinces, citys);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        options.getDialogContainerLayout().setLayoutParams(params);

        //获取当前Activity所在的窗体
        Window dialogWindow = options.getDialog().getWindow();
        //获得窗体的属性
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth(context);
            //将属性设置给窗体
            dialogWindow.setAttributes(lp);
            //底部
            dialogWindow.setGravity(Gravity.BOTTOM);
        }
        return options;
    }

    /**
     * 获取省市选择器
     *
     * @return
     */
    public static OptionsPickerView getProvinceCity(Context context, String title, int colorResId, int textColorResId,
                                                    OnOptionsSelectListener listener, OnDialogListener onDialogListener) {
        OptionsPickerView options = new OptionsPickerBuilder(context, listener)
                .setLayoutRes(R.layout.pickerview_custom_options, v -> {
                    //自定义布局中的控件初始化及事件处理
                    final TextView tvTitle = v.findViewById(R.id.tv_title);
                    final ImageView ivClose = v.findViewById(R.id.iv_close);
                    final TextView tvCancel = v.findViewById(R.id.tv_cancel);
                    final TextView tvConfirm = v.findViewById(R.id.tv_confirm);
                    tvTitle.setText(title);
                    ivClose.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onClose();

                    });
                    tvCancel.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onCancel();
                    });
                    tvConfirm.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onConfirm();
                    });
                })
                .setTitleText(title)
                .setDividerColor(ContextCompat.getColor(context, colorResId))
                .setTextColorCenter(ContextCompat.getColor(context, textColorResId))
                .setCancelColor(ContextCompat.getColor(context, colorResId))
                .setSubmitColor(ContextCompat.getColor(context, colorResId))
                .setContentTextSize(16)
                .setOutSideCancelable(false)
                .setLineSpacingMultiplier(2.5f)
                .isDialog(true)
                .build();

        provinces = ProvinceUtils.getProvinces(context);
        citys = new ArrayList<>();
        for (int i = 0; i < provinces.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）

            for (int j = 0; j < provinces.get(i).getChildren().size(); j++) {//遍历该省份的所有城市
                String cityName = provinces.get(i).getChildren().get(j).getName();
                cityList.add(cityName);//添加城市
            }
            citys.add(cityList);//添加城市数据
        }
        options.setPicker(provinces, citys);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        options.getDialogContainerLayout().setLayoutParams(params);

        //获取当前Activity所在的窗体
        Window dialogWindow = options.getDialog().getWindow();
        //获得窗体的属性
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth(context);
            //将属性设置给窗体
            dialogWindow.setAttributes(lp);
            //底部
            dialogWindow.setGravity(Gravity.BOTTOM);
        }
        return options;
    }

    /**
     * 获取省市选择器
     *
     * @return
     */
    public static OptionsPickerView getProvinceCity(Context context, String title, int colorResId, int textColorResId,
                                                    String cancel, String confirm,
                                                    OnOptionsSelectListener listener, OnDialogListener onDialogListener) {
        OptionsPickerView options = new OptionsPickerBuilder(context, listener)
                .setLayoutRes(R.layout.pickerview_custom_options, v -> {
                    //自定义布局中的控件初始化及事件处理
                    final TextView tvTitle = v.findViewById(R.id.tv_title);
                    final ImageView ivClose = v.findViewById(R.id.iv_close);
                    final TextView tvCancel = v.findViewById(R.id.tv_cancel);
                    final TextView tvConfirm = v.findViewById(R.id.tv_confirm);
                    tvTitle.setText(title);
                    tvCancel.setText(cancel);
                    tvConfirm.setText(confirm);
                    ivClose.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onClose();

                    });
                    tvCancel.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onCancel();
                    });
                    tvConfirm.setOnClickListener(v1 -> {
                        if (onDialogListener != null)
                            onDialogListener.onConfirm();
                    });
                })
                .setTitleText(title)
                .setDividerColor(ContextCompat.getColor(context, colorResId))
                .setTextColorCenter(ContextCompat.getColor(context, textColorResId))
                .setCancelColor(ContextCompat.getColor(context, colorResId))
                .setSubmitColor(ContextCompat.getColor(context, colorResId))
                .setContentTextSize(16)
                .setOutSideCancelable(false)
                .setLineSpacingMultiplier(2.5f)
                .isDialog(true)
                .build();

        provinces = ProvinceUtils.getProvinces(context);
        citys = new ArrayList<>();
        for (int i = 0; i < provinces.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）

            for (int j = 0; j < provinces.get(i).getChildren().size(); j++) {//遍历该省份的所有城市
                String cityName = provinces.get(i).getChildren().get(j).getName();
                cityList.add(cityName);//添加城市
            }
            citys.add(cityList);//添加城市数据
        }
        options.setPicker(provinces, citys);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        options.getDialogContainerLayout().setLayoutParams(params);

        //获取当前Activity所在的窗体
        Window dialogWindow = options.getDialog().getWindow();
        //获得窗体的属性
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth(context);
            //将属性设置给窗体
            dialogWindow.setAttributes(lp);
            //底部
            dialogWindow.setGravity(Gravity.BOTTOM);
        }
        return options;
    }

    public static List<ProvinceBean> getProvinces() {
        return provinces;
    }

    public static List<ArrayList<String>> getCitys() {
        return citys;
    }

    public static List<ArrayList<ArrayList<String>>> getAreas() {
        return areas;
    }

    public static String getAddress(int options1, int options2, int options3) {
        ProvinceBean province = ProvinceUtils.getProvinces().get(options1);
        CityBean city = province.getChildren().size() > 0 ? province.getChildren().get(options2) : new CityBean();
        AreaBean area = city.getChildren().size() > 0 ? city.getChildren().get(options3) : new AreaBean();
        return province.getName() + " " + city.getName() + " " + area.getName();
    }
}
